<!DOCTYPE html>
<html>
<head>
    <title>平台管理</title>
    <#include "/header.html">
    <link
            href="${request.contextPath}/statics/plugins/jquery-layout/jquery.layout-latest.css"
            rel="stylesheet" />
    <style>
        .selectTable th,td{
            text-align: center;
        }
    </style>
</head>
<body>


<div id="rrapp" v-cloak class="container-div ui-layout-center">

    <div v-show="showList">
        <div class="layui-container" style="width: 100%;">
            <div class="layui-row" style="margin-top: 10px;">
                <div class="layui-col-md2">
                    <input type="text" class="form-control" v-model="q.domainCateName" style="width: 100%"
                           @keyup.enter="query" placeholder="类型名称">
                </div>
                <div class="layui-col-md2" style="margin:0 20px">
                    <select class="selectpicker" id="searchSelect"   title="域名库存是否报警"   style="width:100%;" >
                        <option value="">全部</option>
                        <option value="0">否</option>
                        <option value="1">是</option>
                    </select>
                </div>
                <div class="layui-col-md2">
                    <select class="selectpicker" id="searchSelect2" title="域名统计是否开启" style="width:100%;" >
                        <option value="">全部</option>
                        <option value="0">否</option>
                        <option value="1">是</option>
                    </select>
                </div>

                <div class="layui-col-md3" style="margin-left: 20px">
                    <a class="btn btn-default" @click="query">查询</a>
                    <a class="btn btn-primary" @click="add"><i class="fa fa-plus"></i>&nbsp;新增</a>
                    <a class="btn btn-primary" @click="update"><i class="fa fa-pencil-square-o"></i>&nbsp;修改</a>
                    <a class="btn btn-danger" @click="del"><i class="fa fa-trash-o"></i>&nbsp;删除</a>
                </div>

            </div>
        </div>
<div class="col-sm-12 select-info table-striped">
    <table id="bootstrap-table" data-mobile-responsive="true"></table>
</div>
</div>

<div v-show="!showList" class="panel panel-default"  >
    <div class="panel-heading">{{title}}</div>
    <form class="form-horizontal" id="form" style="width: 660px;">
        <div class="form-group">
            <div class="col-sm-2 control-label">类型名称</div>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="user.domainCateName" placeholder="类型名称"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2 control-label">类型key</div>
            <div class="col-sm-10">
                <input type="text" class="form-control" v-model="user.domainCateKey" placeholder="类型key"/>
            </div>
        </div>
       <div class="form-group">
            <div class="col-sm-2 control-label">域名库存是否报警</div>
            <div class="col-sm-10">
                <input type="checkbox" class="checke" id="isOpenWarn">
                <!--<input type="checkbox" class="checke" id="isPull" v-if="user.isPull==1">-->
            </div>
        </div>
        <div class="form-group" v-show="isShowVal">
            <div class="col-sm-2 control-label">平台选择</div>
            <div class="col-sm-10">
                <select class="selectpicker" onchange="getSelectPlat()" data-live-search="true" id="siteSelect" data-actions-box="true" data-select-all-text="全选" data-deselect-all-text="取消全选" data-deselect-all-text="全选" title="请选择平台名称" multiple>
                </select>
            </div>
        </div>
        <div class="form-group" v-if="isShowVal">
            <div class="col-sm-2 control-label">域名库存报警警戒值</div>
            <div class="col-sm-10">
                <!--<textarea class="form-control" v-model="user.alarmNumArr"  placeholder="请输入域名库存报警警戒值(每输入一个值按回车键进行换行操作)" id="num"  autocomplete="off" rows="8"></textarea>-->
                <!--<input type="text" class="form-control" v-model="user.alarmNum" placeholder="域名库存报警警戒值"/>-->
                <table class="table table-hover table-bordered selectTable">
                    <thead>
                       <tr>
                           <th>平台名称</th>
                           <th>报警值</th>
                       </tr>
                    </thead>
                    <tbody id="warnTb">

                    </tbody>
                </table>
            </div>
        </div>
        <!--<div class="form-group" v-if="isShowVal">-->
            <!--<div class="col-sm-2 control-label">默认报警警戒值</div>-->
            <!--<div class="col-sm-10">-->
               <!--<input type="text" class="form-control" v-model="user.alarmNum" placeholder="默认报警警戒值"/>-->
            <!--</div>-->
        <!--</div>-->
        <div class="form-group">
            <div class="col-sm-2 control-label">是否开启域名统计</div>
            <div class="col-sm-10">
                <input type="checkbox" class="checke" id="isOpenStatic">
                <!--<input type="checkbox" class="checke" id="isPull" v-if="user.isPull==1">-->
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-2 control-label">排序号</div>
            <div class="col-sm-10">
                <input type="number" class="form-control" v-model="user.sort" placeholder="排序号" style="width: 100px;"/>
            </div>
        </div>
       <div class="form-group">
            <div class="col-sm-2 control-label"></div>
            <input type="button" ref="submitBtn" class="btn btn-primary" @click="saveOrUpdate" value="确定"/>
            &nbsp;&nbsp;<input type="button" class="btn btn-warning" @click="reload" value="返回"/>
        </div>
    </form>

</div>


</div>


<script
        src="${request.contextPath}/statics/plugins/jquery-layout/jquery.layout-latest.js"></script>


<!-- <script src="${request.contextPath}/statics/js/modules/sys/user.js?_${.now?long}"></script>
-->
<script>
  var editPlatformIdArr = [];
  var editAlarmNumArr = [];
  function getSelectPlat() {
      setTabData();
   }
   function setTabData() {
       var title = $("#siteSelect").find("option:selected");
      // console.log('11111111');
       var selectText = [];
       title.map(function (item) {
           //console.log($(this).text());
           if(selectText.indexOf($(this).text()) == -1){
               selectText.push($(this).text())
           }
       });
       showTab(selectText);
   }
  function showTab(data) {
      //$("#warnTb").empty();
       var tbodyHtml = '';
       var defaultData = [];
       var isHasVal = false;
       var selectArr = $("#siteSelect").val();
       if(editPlatformIdArr.length>0&&editAlarmNumArr.length>0){
           for(var j =0;j<editPlatformIdArr.length;j++){
               defaultData.push({
                   platformId:editPlatformIdArr[j],
                   alarmNum:editAlarmNumArr[j]
               });
           }
       }
     // console.log(selectArr)
      for(var i=0;i<data.length;i++){
           if(defaultData.length > 0 ){
               //console.log('33333333')
               isHasVal = false;
               for(var k =0;k<defaultData.length;k++){
                   if(selectArr[i] == defaultData[k].platformId){
                       //console.log('222222')
                       tbodyHtml = tbodyHtml +  '<tr><td>'+data[i]+'</td><td><input value="'+defaultData[k].alarmNum+'" class="form-control" placeholder="请输入报警警戒值" type="number" /></td></tr>';
                       isHasVal = true;
                   }
               }
               if(!isHasVal){
                   tbodyHtml = tbodyHtml +  '<tr><td>'+data[i]+'</td><td><input class="form-control" placeholder="请输入报警警戒值" type="number" /></td></tr>';
               }
           }else{
              // console.log('44444444')
              tbodyHtml = tbodyHtml +  '<tr><td>'+data[i]+'</td><td><input class="form-control" placeholder="请输入报警警戒值" type="number" /></td></tr>';
          }

      }
      console.log(tbodyHtml);
      $("#warnTb").html(tbodyHtml);
     console.log( $("#warnTb").html());
  }
    $(document)
        .ready(
            function() {
                $('body').layout({
                    west__size : 185
                });
                /* queryUserList();*/
               $('#bootstrap-table')
                    .bootstrapTable(
                        {
                            method : 'post', // 服务器数据的请求方式 get or post
                            url : baseURL + 'domaincate/findDomainCatePage', // 服务器数据的加载地址
                            showRefresh : true,
                            showToggle : true,
                            showColumns : true,
                            //showExport :true,
                            sortable: false,
                            sortName:"sort",// 排序列名称
                            sortOrder: "asc",
                            iconSize : 'outline',
                            toolbar : '#exampleToolbar',
                            striped : true, // 设置为true会有隔行变色效果
                            dataType : "json", // 服务器返回的数据类型
                            pagination : true, // 设置为true会在底部显示分页条
                            // queryParamsType : "limit",
                            // //设置为limit则会发送符合RESTFull格式的参数
                            singleSelect : false, // 设置为true将禁止多选
                            // contentType : "application/x-www-form-urlencoded",
                            // //发送到服务器的数据编码类型
                            pageSize : 10, // 如果设置了分页，每页数据条数
                            pageNumber : 1, // 如果设置了分布，首页页码
                            // search : true, // 是否显示搜索框
                            //showColumns : false, // 是否显示内容下拉框（选择显示的列）
                            sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者
                            // "server"
                            queryParams : function(params) {
                                //console.log(params)
                                return {
                                    // 说明：传入后台的参数包括offset开始索引，limit步长，sort排序列，order：desc或者,以及所有列的键值对
                                    limit : params.limit,
                                    page : (params.offset/params.limit) + 1,
                                    domainCateName : vm.q.domainCateName,
                                    isAlarm:$("#searchSelect").val(),
                                    domainStatisShow:$("#searchSelect2").val()
                                    // sidx: params.sort,      //排序列名
                                    //order: params.order //排位命令（desc，asc）
                                    /* sort:"userId",
                                    order:"desc" */
                                };
                            },
                            // //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
                            // queryParamsType = 'limit' ,返回参数必须包含
                            // limit, offset, search, sort, order 否则, 需要包含:
                            // pageSize, pageNumber, searchText, sortName,
                            // sortOrder.
                            // 返回false将会终止请求
                            columns : [
                                {
                                    checkbox : true
                                },

                                {
                                    field : 'domainCateName',
                                    align:'center',
                                    title : '类型名称'
                                },
                                {
                                    field : 'domainCateKey', // 列字段名
                                    align:'center',
                                    title : '类型key'// 列标题
                                },
                                {
                                    field : 'isAlarm', // 列字段名
                                    align:'center',
                                    title : '域名库存是否报警',// 列标题
                                    formatter : function(
                                        value, row,
                                        index) {
                                        var e = row.isAlarm == 0 ? '<span>否</span>': '<span>是</span>';
                                        return e ;
                                    }
                                },
                                {
                                    field : 'domainStatisShow', // 列字段名
                                    align:'center',
                                    title : '域名统计是否开启',// 列标题
                                    formatter : function(
                                        value, row,
                                        index) {
                                        var e = row.domainStatisShow == 0 ? '<span>否</span>': '<span>是</span>';
                                        return e ;
                                    }
                                },
                                {
                                    field : 'createTime',
                                    title : '创建时间',
                                    align:'center',
                                    width:200,
                                    titleTooltip: "this is name"
                                },
                                {
                                    field : 'sort',
                                    align:'center',
                                    width:100,
                                    title : '排序'
                                },
                                {
                                    title : '操作',
                                    field : 'id',
                                    width:330,
                                    align : 'center',
                                    formatter : function(
                                        value, row,
                                        index) {

                                        var e = '<a  class="btn btn-primary btn-sm '
                                            + ''
                                            + '" href="#" mce_href="#" title="编辑" onclick="edit(\''
                                            + row.id+ '\')"><i class="fa fa-edit " style="margin-right: 5px"></i>编辑</a> ';
                                        var d = '<a class="btn btn-danger btn-sm '
                                            + ''
                                            + '" href="#" title="删除"  mce_href="#" onclick="remove(\''
                                            + row.id + '\')"><i class="fa fa-remove" style="margin-right: 5px"></i>删除</a> ';
                                        var f = row.isAlarm ? '<a class="btn btn-success btn-sm '
                                            + ''
                                            + '" href="domainDetails.html?id='+row.id+'" title="详情"  mce_href="#" ><i class="fa fa-menu" style="margin-right: 5px"></i>详情</a> ' :'';
                                        return e + d + f;
                                    }
                                } ]
                        });
            });
    var vm = new Vue({
        el : '#rrapp',
        data : {
            q : {
                domainCateName : null
            },
             showList : true,
             isShowVal:false,
             title : null,
             user : {
                domainCateName:'',
                domainCateKey:'',
                 alarmNum:'',
                 alarmNumArr:[],
                 sort:1
            }
        },
        methods : {
            query : function() {
                vm.reload();
            },
            getAllPlat:function () {
                $.ajax({
                    type : "get",
                    url : baseURL+"platform/findAllPlatform",
                    dataType : "json",
                    async:false,
                    success: function(data) {
                        if(data.code==0) {
                            var _html = ''
                            var _arr = []
                            for (var i = 0; i < data.platformList.length; i++) {
                                _html = _html + '<option value="' + data.platformList[i].platformId + '">' + data.platformList[i].nickName + '</option>'
                                _arr.push(data.platformList[i].platformId)
                            }
                            $('#siteSelect').html(_html);
                            //$('#siteSelect').val(_arr)
                            $('#siteSelect').selectpicker('refresh');

                        }
                    }
                });
            },
            add : function() {
                vm.showList = false;
                vm.isShowVal = false;
                vm.title = "新增";
                vm.roleList = {};
                vm.user = {
                    domainCateName:'',
                    domainCateKey:'',
                    alarmNum:'',
                    sort:1,
                    alarmNumArr:[]
                };
                 editPlatformIdArr = [];
                 editAlarmNumArr = [];
                $("#isOpenWarn").prop("checked",false);
                $("#isOpenStatic").prop("checked",false);
                vm.getAllPlat();
            },
            update : function() {
                // console.log(11111)
                vm.user = {
                    domainCateName:'',
                    domainCateKey:'',
                    alarmNum:'',
                    sort:1,
                    alarmNumArr:[]
                };
                $("#isOpenWarn").prop("checked",false);
                $("#isOpenStatic").prop("checked",false);
                var userId = getSelectedRow();
                if (userId == null) {
                    return;
                }
                vm.title = "修改";
               // console.log(userId);
                vm.getUser(userId.id);
                vm.getAllPlat();
            },
            del : function() {
                var userIds = getSelectedRows();
                var delArr = [];
                if (userIds == null) {
                    return;
                }
                userIds.map(function (item) {
                    delArr.push(item.id);
                });
                confirm('确定要删除选中的记录？', function() {
                    $.ajax({
                        type : "POST",
                        url : baseURL + "domaincate/deleteDomainCate",
                        contentType : "application/json",
                        data : JSON.stringify(delArr),
                        success : function(r) {
                            if (r.code == 0) {
                                alert('操作成功', function() {
                                    vm.reload();
                                });
                            } else {
                                alert(r.msg);
                            }
                        }
                    });
                });
            },
            saveOrUpdate : function() {
                var url = vm.user.id == null ? "domaincate/saveDomainCate"
                    : "domaincate/updateDomainCate";
                var arrs = [];
                var params = {};
                //console.log(vm.user.platformId);
                var btn = vm.$refs.submitBtn;
                var reg = /^[1-9]\d*$/;
                if(checkIsBank(vm.user.domainCateName) || checkIsBank(vm.user.domainCateKey)){
                    alert("全部为必填字段!");
                    return false;
                }
               // console.log( $("#siteSelect").val());
                vm.user.isAlarm = $("#isOpenWarn").is(":checked")?1:0;
                vm.user.domainStatisShow = $("#isOpenStatic").is(":checked")?1:0;
               // console.log(vm.user.alarmNumArr)
                if(vm.user.isAlarm){

                    if(!$("#siteSelect").val() && vm.user.alarmNumArr.length<1){
                        vm.user.alarmNumArr = [];
                        vm.user.platformIdArr = [];
                    }else{

                    var arr  = [];
                    $("#warnTb").find('input').map(function (item) {
                        arr.push($(this).val());
                    });
                    var isNum = true;
                    arr.map(function (item) {
                        if(item !='' ){
                            arrs.push(item);
                        }
                    })
                    arrs.map(function (item) {
                        if(!reg.test(item)){
                            isNum = false;
                            return false;
                        }
                    });
                    if(!isNum){
                        alert("请输入正整数报警值!");
                        return false;
                    }
                  // console.log(arrs)
                  // console.log($("#siteSelect").val());
                    if(!$("#siteSelect").val()){
                        alert("请选择平台!");
                        return false;
                    }
                    if(arrs.length != $("#siteSelect").val().length){
                        alert("请检查域名库存报警警戒值是否与平台选择一一对应!");
                        return false;
                    }
                     vm.user.platformIdArr = $("#siteSelect").val();
                    }
                }else{
                    vm.user.alarmNumArr = [];
                    vm.user.platformIdArr = [];
                }
                params = vm.user.id ? {
                    id:vm.user.id,
                    alarmNumArr:arrs,
                    alarmNum:vm.user.alarmNum,
                    domainCateKey:vm.user.domainCateKey,
                    domainCateName:vm.user.domainCateName,
                    domainStatisShow:vm.user.domainStatisShow,
                    isAlarm:vm.user.isAlarm,
                    platformIdArr:vm.user.platformIdArr,
                    sort:vm.user.sort
                }:{
                    alarmNumArr:arrs,
                    alarmNum:vm.user.alarmNum,
                    domainCateKey:vm.user.domainCateKey,
                    domainCateName:vm.user.domainCateName,
                    domainStatisShow:vm.user.domainStatisShow,
                    isAlarm:vm.user.isAlarm,
                    platformIdArr:vm.user.platformIdArr,
                    sort:vm.user.sort
                };
                //console.log(params);
                // return;
                btn.disabled = true;
                $.ajax({
                    type : "POST",
                    url : baseURL + url,
                    contentType : "application/json",
                    data : JSON.stringify(params),
                    success : function(r) {
                        btn.disabled = false;
                        if (r.code === 0) {
                            alert('操作成功', function() {
                                vm.reload();
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            getUser : function(id) {
                $.ajax({
                    type : "POST",
                    url : baseURL + "domaincate/findDomainCateById",
                    contentType : "application/json",
                    data : JSON.stringify({id:id}),
                    success : function(r) {
                        if (r.code === 0) {
                            vm.user.domainCateName = r.result.domainCateName;
                            vm.user.domainCateKey = r.result.domainCateKey;
                            vm.user.id = r.result.id;
                            r.result.isAlarm?$("#isOpenWarn").prop("checked",true):$("#isOpenWarn").prop("checked",false);
                            vm.user.alarmNumArr  =  r.result.alarmNumArr || [];
                            vm.user.sort = r.result.sort;
                            r.result.domainStatisShow?$("#isOpenStatic").prop("checked",true):$("#isOpenStatic").prop("checked",false);
                            r.result.isAlarm?vm.isShowVal = true : vm.isShowVal = false;
                            var _arr = r.result.platformIdArr || [];
                            //console.log(_arr);
                            $('#siteSelect').val(_arr)
                            $('#siteSelect').selectpicker('refresh');
                            editPlatformIdArr = _arr;
                            editAlarmNumArr = r.result.alarmNumArr;
                            vm.user.alarmNum = r.result.alarmNum;
                            vm.showList = false;
                            setTimeout(function () {
                                setTabData();
                            },300);

                        } else {
                            alert(r.msg);
                        }
                    }
                });
            },
            reload : function() {
                vm.showList = true;
                // var opt = {
                //     url: baseURL + 'domaincate/findDomainCatePage',
                //     silent: true,
                //     query:{
                //         limit : 10,
                //         page : 0,
                //         domainCateName : vm.q.domainCateName,
                //         isAlarm:$("#searchSelect").val(),
                //         domainStatisShow:$("#searchSelect2").val()
                //     }
                // };

                $('#bootstrap-table').bootstrapTable('refresh',
                    {
                        domainCateName : vm.q.domainCateName,
                        isAlarm:$("#searchSelect").val(),
                        domainStatisShow:$("#searchSelect2").val()
                    });

            }
        }
    });
    $(document).on("click","#isOpenWarn",function () {
        if($(this).is(":checked")){
           vm.isShowVal = true;
        }else{
            vm.isShowVal = false;
        }
    });
    $('#siteSelect').on('changed.bs.select',function(e){
          //console.log($(this).html());
    });
    function edit(id) {
        if (id == null) {
            return;
        }
        //console.log(2222)
        vm.user = {
            domainCateName:'',
            domainCateKey:'',
            defaultAlarmNum:'',
            alarmNumArr:[]
        };
        $("#isOpenWarn").prop("checked",false);
        $("#isOpenStatic").prop("checked",false);
        vm.showList = false;
        vm.title = "修改";
        vm.getAllPlat();
        vm.getUser(id);
       }

    function remove(id) {
        confirm('确定要删除选中的记录？', function() {
            $.ajax({
                type : "POST",
                url : baseURL + "domaincate/deleteDomainCate",
                contentType : "application/json",
                data : JSON.stringify([id]),
                success : function(r) {
                    if (r.code == 0) {
                        alert('操作成功', function() {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        });
    }

</script>


</body>
</html>